<template>
  <div class="create-outfit">
    <div class="page-header">
      <h2>{{ isEdit ? '编辑搭配' : '创建搭配' }}</h2>
      <p>{{ isEdit ? '修改搭配信息' : '选择衣服，创建你的完美搭配' }}</p>
    </div>

    <el-row :gutter="20">
      <!-- 左侧：衣服选择 -->
      <el-col :span="16">
        <el-card class="clothing-selection">
          <template #header>
            <div class="card-header">
              <span>选择衣服</span>
              <el-input
                v-model="searchKeyword"
                placeholder="搜索衣服..."
                style="width: 200px;"
                @input="loadClothingList"
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </div>
          </template>

          <!-- 分类筛选 -->
          <div class="category-tabs">
            <el-tabs v-model="activeCategory" @tab-change="handleCategoryChange">
              <el-tab-pane label="全部" name="all" />
              <el-tab-pane
                v-for="category in categories"
                :key="category.id"
                :label="category.name"
                :name="category.id.toString()"
              />
            </el-tabs>
          </div>

          <!-- 衣服网格 -->
          <div class="clothing-grid" v-loading="loadingClothes">
            <div
              v-for="item in clothingList"
              :key="item.id"
              class="clothing-item"
              :class="{ selected: selectedClothes.some(c => c.id === item.id) }"
              @click="toggleClothingSelection(item)"
            >
              <div class="clothing-image">
                <img :src="item.main_image || '/placeholder.jpg'" :alt="item.name" />
                <div class="selection-overlay" v-if="selectedClothes.some(c => c.id === item.id)">
                  <el-icon class="check-icon"><Check /></el-icon>
                </div>
              </div>
              <div class="clothing-info">
                <p class="clothing-name">{{ item.name }}</p>
                <p class="clothing-category">{{ getCategoryName(item.category_id) }}</p>
              </div>
            </div>
          </div>

          <!-- 分页 -->
          <div class="pagination-wrapper">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :total="total"
              :page-sizes="[12, 24, 48]"
              layout="total, sizes, prev, pager, next, jumper"
              @current-change="loadClothingList"
              @size-change="loadClothingList"
            />
          </div>
        </el-card>
      </el-col>

      <!-- 右侧：搭配信息 -->
      <el-col :span="8">
        <el-card class="outfit-form">
          <template #header>
            <span>搭配信息</span>
          </template>

          <el-form
            ref="formRef"
            :model="outfitForm"
            :rules="outfitRules"
            label-width="80px"
          >
            <el-form-item label="搭配名称" prop="name">
              <el-input v-model="outfitForm.name" placeholder="请输入搭配名称" />
            </el-form-item>

            <el-form-item label="风格" prop="style">
              <el-select v-model="outfitForm.style" placeholder="选择风格">
                <el-option label="休闲" value="casual" />
                <el-option label="正式" value="formal" />
                <el-option label="商务" value="business" />
                <el-option label="运动" value="sport" />
                <el-option label="派对" value="party" />
                <el-option label="约会" value="date" />
              </el-select>
            </el-form-item>

            <el-form-item label="季节" prop="season">
              <el-select v-model="outfitForm.season" placeholder="选择季节">
                <el-option label="春季" value="spring" />
                <el-option label="夏季" value="summer" />
                <el-option label="秋季" value="autumn" />
                <el-option label="冬季" value="winter" />
                <el-option label="四季" value="all" />
              </el-select>
            </el-form-item>

            <el-form-item label="场合" prop="occasion">
              <el-input v-model="outfitForm.occasion" placeholder="请输入适用场合" />
            </el-form-item>

            <el-form-item label="描述" prop="description">
              <el-input
                v-model="outfitForm.description"
                type="textarea"
                :rows="3"
                placeholder="描述这套搭配..."
              />
            </el-form-item>

            <el-form-item label="评分" prop="rating">
              <el-rate v-model="outfitForm.rating" />
            </el-form-item>
          </el-form>

          <!-- 已选择的衣服 -->
          <div class="selected-clothes">
            <h4>已选择的衣服 ({{ selectedClothes.length }})</h4>
            <div class="selected-list">
              <div
                v-for="item in selectedClothes"
                :key="item.id"
                class="selected-item"
              >
                <img :src="item.main_image || '/placeholder.jpg'" :alt="item.name" />
                <span>{{ item.name }}</span>
                <el-button
                  size="small"
                  type="danger"
                  @click="removeClothing(item)"
                  circle
                >
                  <el-icon><Close /></el-icon>
                </el-button>
              </div>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="form-actions">
            <el-button type="primary" @click="saveOutfit" :loading="saving">
              {{ isEdit ? '更新搭配' : '保存搭配' }}
            </el-button>
            <el-button @click="resetForm">重置</el-button>
            <el-button @click="goBack">返回</el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { clothingAPI, categoryAPI, outfitAPI } from '@/api'

const router = useRouter()
const route = useRoute()

// 编辑模式
const isEdit = computed(() => !!route.params.id)
const outfitId = computed(() => route.params.id)

// 响应式数据
const formRef = ref()
const saving = ref(false)
const loadingClothes = ref(false)
const searchKeyword = ref('')
const activeCategory = ref('all')
const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)

const categories = ref([])
const clothingList = ref([])
const selectedClothes = ref([])

// 搭配表单
const outfitForm = reactive({
  name: '',
  style: '',
  season: '',
  occasion: '',
  description: '',
  rating: 0
})

// 表单验证规则
const outfitRules = {
  name: [
    { required: true, message: '请输入搭配名称', trigger: 'blur' },
    { min: 2, max: 50, message: '搭配名称长度在2-50个字符', trigger: 'blur' }
  ],
  style: [
    { required: true, message: '请选择风格', trigger: 'change' }
  ],
  season: [
    { required: true, message: '请选择季节', trigger: 'change' }
  ]
}

// 获取分类名称
const getCategoryName = (categoryId) => {
  const category = categories.value.find(c => c.id === categoryId)
  return category ? category.name : '未知分类'
}

// 加载分类列表
const loadCategories = async () => {
  try {
    const response = await categoryAPI.getList()
    if (response.code === 200) {
      categories.value = response.data || []
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
  }
}

// 加载衣服列表
const loadClothingList = async () => {
  try {
    loadingClothes.value = true

    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      keyword: searchKeyword.value || undefined,
      category_id: activeCategory.value !== 'all' ? activeCategory.value : undefined,
      status: 'available' // 只显示可用的衣服
    }

    const response = await clothingAPI.getList(params)

    if (response.code === 200) {
      clothingList.value = response.data.list || []
      total.value = response.data.total || 0
    }
  } catch (error) {
    console.error('获取衣服列表失败:', error)
    ElMessage.error('获取衣服列表失败')
  } finally {
    loadingClothes.value = false
  }
}

// 分类切换
const handleCategoryChange = () => {
  currentPage.value = 1
  loadClothingList()
}

// 切换衣服选择
const toggleClothingSelection = (item) => {
  const index = selectedClothes.value.findIndex(c => c.id === item.id)
  if (index > -1) {
    selectedClothes.value.splice(index, 1)
  } else {
    selectedClothes.value.push(item)
  }
}

// 移除选中的衣服
const removeClothing = (item) => {
  const index = selectedClothes.value.findIndex(c => c.id === item.id)
  if (index > -1) {
    selectedClothes.value.splice(index, 1)
  }
}

// 保存搭配
const saveOutfit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()

    if (selectedClothes.value.length === 0) {
      ElMessage.warning('请至少选择一件衣服')
      return
    }

    saving.value = true

    const submitData = {
      ...outfitForm,
      clothes: selectedClothes.value.map(item => ({
        clothing_id: item.id,
        position: getCategoryName(item.category_id),
        is_main: false
      }))
    }

    let response
    if (isEdit.value) {
      response = await outfitAPI.update(outfitId.value, submitData)
    } else {
      response = await outfitAPI.create(submitData)
    }

    if (response.code === 200) {
      ElMessage.success(isEdit.value ? '搭配更新成功' : '搭配创建成功')
      router.push('/outfits')
    } else {
      throw new Error(response.message || '操作失败')
    }
  } catch (error) {
    console.error('保存搭配失败:', error)
    ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
  } finally {
    saving.value = false
  }
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  selectedClothes.value = []
  Object.assign(outfitForm, {
    name: '',
    style: '',
    season: '',
    occasion: '',
    description: '',
    rating: 0
  })
}

// 返回
const goBack = () => {
  router.push('/outfits')
}

// 加载编辑数据
const loadOutfitData = async () => {
  if (!isEdit.value) return

  try {
    const response = await outfitAPI.getById(outfitId.value)
    if (response.code === 200) {
      const data = response.data

      // 填充表单数据
      Object.assign(outfitForm, {
        name: data.name || '',
        style: data.style || '',
        season: data.season || '',
        occasion: data.occasion || '',
        description: data.description || '',
        rating: data.rating || 0
      })

      // 填充选中的衣服
      if (data.clothes && data.clothes.length > 0) {
        selectedClothes.value = data.clothes
      }
    }
  } catch (error) {
    console.error('加载搭配数据失败:', error)
    ElMessage.error('加载搭配数据失败')
  }
}

// 页面初始化
onMounted(() => {
  loadCategories()
  loadClothingList()
  if (isEdit.value) {
    loadOutfitData()
  }
})
</script>

<style scoped>
.create-outfit {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.clothing-selection {
  height: calc(100vh - 200px);
  overflow: hidden;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.category-tabs {
  margin-bottom: 20px;
}

.clothing-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 16px;
  max-height: 400px;
  overflow-y: auto;
  padding: 16px 0;
}

.clothing-item {
  cursor: pointer;
  border: 2px solid transparent;
  border-radius: 8px;
  padding: 8px;
  transition: all 0.3s ease;
  position: relative;
}

.clothing-item:hover {
  border-color: #409EFF;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
}

.clothing-item.selected {
  border-color: #67C23A;
  background-color: #f0f9ff;
}

.clothing-image {
  position: relative;
  width: 100%;
  height: 120px;
  border-radius: 6px;
  overflow: hidden;
  background: #f5f5f5;
}

.clothing-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.selection-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(103, 194, 58, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
}

.check-icon {
  color: white;
  font-size: 24px;
}

.clothing-info {
  padding: 8px 0;
  text-align: center;
}

.clothing-name {
  margin: 0 0 4px 0;
  font-size: 12px;
  font-weight: 500;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.clothing-category {
  margin: 0;
  font-size: 11px;
  color: #999;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: center;
}

.outfit-form {
  height: calc(100vh - 200px);
  overflow-y: auto;
}

.selected-clothes {
  margin: 20px 0;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
}

.selected-clothes h4 {
  margin: 0 0 12px 0;
  color: #333;
  font-size: 14px;
}

.selected-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.selected-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px;
  background: white;
  border-radius: 4px;
  border: 1px solid #e0e0e0;
}

.selected-item img {
  width: 40px;
  height: 40px;
  object-fit: cover;
  border-radius: 4px;
}

.selected-item span {
  flex: 1;
  font-size: 12px;
  color: #333;
}

.form-actions {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #eee;
  display: flex;
  gap: 12px;
}

.form-actions .el-button {
  flex: 1;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .clothing-grid {
    grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
  }
}

@media (max-width: 768px) {
  .create-outfit {
    padding: 16px;
  }

  .clothing-grid {
    grid-template-columns: repeat(auto-fill, minmax(80px, 1fr));
    gap: 12px;
  }

  .clothing-image {
    height: 80px;
  }
}
</style>
